package com.lunatic.shiro.realm;

import com.lunatic.shiro.pojo.Account;
import com.lunatic.shiro.service.AccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;

public class AccountRealm extends AuthorizingRealm {

    @Autowired
    private AccountService accountService;


    /**
     * 授权
     *
     * @param principalCollection 主体集合
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取当前用户的登录信息
        Account account = (Account) SecurityUtils.getSubject().getPrincipal();

        // 设置角色
        HashSet<String> roles = new HashSet<>();
        roles.add(account.getRole());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);

        // 设置权限
        info.addStringPermission(account.getPerms());
        return info;
    }


    /**
     * 认证
     *
     * @param authenticationToken 身份验证令牌
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Account account = accountService.FIND_BY_NAME(token.getUsername());

        // 验证用户名和密码，用户名不正确会抛出一个异常，密码不正确会抛出一个异常，我们只需要捕获这两个异常来判断是 用户名或密码错误
        if (account != null) {
            return new SimpleAuthenticationInfo(account, account.getPassword(), getName());
        }

        return null;
    }
}
